﻿var defaultAvatar = "~/Images/avatar.png";
var Profile = function (data) {
    var selfProfile = this;
    selfProfile.owner = ko.observable(data.owner);
    selfProfile.isLoadedAbout = ko.observable(data.isLoadedAbout);
    selfProfile.isEdittingAbout = ko.observable(false);
    selfProfile.aboutTabMode = ko.computed(function () {
        return selfProfile.isLoadedAbout() ? (selfProfile.isEdittingAbout() ? "tab-about-edit" : "tab-about") : "tab-loading";
    });
    selfProfile.about = new About(data.about);
    selfProfile.EditAbout = function (current) {
        if (current.owner()) {
            selfProfile.isEdittingAbout(true);
            $('#about form').parsley();
            $('#about .easypiechart').easyPieChart();
            $('#about input[type=file]').filestyle({ input: false, buttonText: "Change Avatar", buttonName: "btn-default", size: "xs", iconName: "fa fa-cloud-upload text" });
        } else {
            alert("Sorry! you donot have permission to edit this content");
        }
    };
    selfProfile.UpdateAbout = function (formElement) {
        if ($(formElement).parsley('isValid')) {
            var url = formElement.action;
            $.ajax({
                url: url,
                type: "POST",
                dataType: "json",
                data: selfProfile.about,
                beforeSend: function () {
                    $(formElement).find('button[type=submit]').addClass("active disabled").text("Saving...");
                    $(formElement).find('#spin-save-about').addClass("show inline");
                },
                success: function (data) {
                    var success = data.success;
                    if (success) {
                        selfProfile.isEdittingAbout(false);
                        $('#about .easypiechart').easyPieChart();
                    } else {
                        $(formElement).find('button[type=submit]').removeClass("active disabled").text("Save");
                        $(formElement).find('#spin-save-about').removeClass("show inline");
                        alert("Cannot save changes! please try again later");
                    }
                },
                error: function () {
                    $(formElement).find('button[type=submit]').removeClass("active disabled").text("Save");
                    $(formElement).find('#spin-save-about').removeClass("show inline");
                    alert("Cannot save changes! please try again later");
                },
            });
        }
    };
    selfProfile.ChangeAvatar = function (current, event) {
        if (current.owner()) {
            var files = event.target.files;
            if (files.length > 0) {
                var file = files[0];
                UploadFile(file, $(event.target).data('url'));
            }
        } else {
            alert("Sorry! you donot have permission to change the avatar");
        }
    };
    selfProfile.RemoveAvatar = function (current, event) {
        if (current.owner()) {
            if (confirm("Are you sure to remove the avatar?")) {
                $.ajax({
                    url: "/Diary/RemoveAvatar",
                    type: "POST",
                    dataType: "json",
                    data: "",
                    beforeSend: function () {
                        $(event.currentTarget).addClass("disabled");
                    },
                    success: function (data) {
                        var success = data.success;
                        if (success) {
                            selfProfile.about.avatar(data.avatar);
                        } else {
                            alert("Cannot remove avatar! please try again later");
                        }
                    },
                    error: function () {
                        alert("Cannot remove avatar! please try again later");
                    },
                    complete: function () {
                        $(event.currentTarget).removeClass("disabled");
                    },
                });
            }
        } else {
            alert("Sorry! you donot have permission to remove the avatar");
        }
    };
    selfProfile.isLoadedFriends = ko.observable(data.isLoadedFriend);
    selfProfile.friendTabMode = ko.computed(function() {
        return selfProfile.isLoadedFriends() ? "tab-friend" : "tab-loading";
    });
    selfProfile.friends = new Friends(data.friends);
    selfProfile.Unfriend = function (current, event) {
        if (selfProfile.owner() && confirm("Are you sure to unfriend with " + current.displayName() + "?")) {
            selfProfile.friends.allFriends.remove(current);
        }
    };
    selfProfile.SendFriendRequest = function(current, event) {
        selfProfile.friends.suggestedFriends.remove(current);
    };
    selfProfile.ConfirmFriendRequest = function (current, event) {
        current.friendMode("friend");
        selfProfile.friends.allFriends.push(current);
        selfProfile.friends.requestedFriends.remove(current);
    };
    selfProfile.RefuseFriendRequest = function(current, event) {
        selfProfile.friends.requestedFriends.remove(current);
    };
};
var About = function (aboutData) {
    var selfAbout = this;
    selfAbout.account = ko.observable(aboutData.account);
    selfAbout.email = ko.observable(aboutData.email);
    selfAbout.displayName = ko.observable(aboutData.displayName);
    selfAbout.introduce = ko.observable(aboutData.introduce);
    selfAbout.job = ko.observable(aboutData.job);
    selfAbout.school = ko.observable(aboutData.school);
    selfAbout.address = ko.observable(aboutData.address);
    selfAbout.description = ko.computed(function () {
        return (selfAbout.job() == null || selfAbout.job().length == 0) ? ((selfAbout.school() == null || selfAbout.school().length == 0) ? "" : selfAbout.school()) : selfAbout.job();
    });
    selfAbout.avatar = ko.observable(aboutData.avatar);
};
var Friends = function(friendsData) {
    var selfFriends = this;
    selfFriends.allFriends = ko.observableArray(ko.utils.arrayMap(friendsData.allFriends, function(item) {
        var friendItem = new FriendItem(item);
        return friendItem;
    }));
    selfFriends.suggestedFriends = ko.observableArray(ko.utils.arrayMap(friendsData.suggestedFriends, function(item) {
        var friendItem = new FriendItem(item);
        friendItem.friendMode("suggest-friend");
        return friendItem;
    }));
    selfFriends.requestedFriends = ko.observableArray(ko.utils.arrayMap(friendsData.requestedFriends, function(item) {
        var friendItem = new FriendItem(item);
        friendItem.friendMode("request-friend");
        return friendItem;
    }));
}
var FriendItem = function(friendItemData) {
    var selfFriendItem = this;
    selfFriendItem.displayName = ko.observable(friendItemData.displayName);
    selfFriendItem.avatar = ko.observable(friendItemData.avatar);
    selfFriendItem.description = ko.observable(friendItemData.description);
    selfFriendItem.profileUrl = ko.observable(friendItemData.profileUrl);
    selfFriendItem.friendMode = ko.observable("friend");
}
var viewModel = new Profile(data);
ko.applyBindings(viewModel);

// upload avatar
function UploadFile(file, url) {
    var fileName = file.name;
    var fd = new FormData();
    fd.append("fileData", file);
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
    xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
    xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
    xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
    xhr.open("POST", url, true);
    xhr.send(fd);
}

function UploadProgress(evt) {
    if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        $("#uploading").text(percentComplete + "% ");
    }
}

function UploadComplete(evt) {
    if (evt.target.status == 200) {
        console.log(evt.target.responseText);
        var data = JSON.parse(evt.target.responseText);
        var success = data.success;
        if (success) {
            var avatar = data.avatar;
            viewModel.about.avatar(data.avatar);
        } else {
            alert("Error: " + data.error);
        }
    }
    else {
        alert("Error Uploading File");
    }
}

function UploadFailed(evt) {
    alert("There was an error attempting to upload the file.");
}

function UploadCanceled(evt) {
    alert("The upload has been canceled by the user or the browser dropped the connection.");
}